package com.ruoyi.management.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.management.base.config.TemplateMessageSender;
import com.ruoyi.management.base.utils.DateUtils;
import com.ruoyi.management.controller.TemplateController;
import com.ruoyi.management.dao.mapper.BillingMapper;
import com.ruoyi.management.dao.mapper.WxMapper;
import com.ruoyi.management.pojo.entity.*;
import com.ruoyi.management.pojo.po.QldbqyinfoPO;
import com.ruoyi.management.pojo.po.QldbydyzPO;
import com.ruoyi.management.pojo.vo.DbdfVO;
import com.ruoyi.management.pojo.vo.QldbydbmxVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class BillingTaskImpl {
    @Autowired
    private BillingMapper billingMapper;
    @Autowired
    private TemplateController templateController;
    @Autowired
    private WxMapper wxMapper;

    /**
     * 项目启动时立即执行
     */
    @PostConstruct
    public void init() throws Exception {
//        BillGeneration();
//        BillGeneration2();
    }

    /**
     * 每月27日发送通知给项目运营人员提醒进行数据核查工作
     */
    @Scheduled(cron = "0 0 0 27 * ?")
    //每月27日发送通知给项目运营人员提醒进行数据核查工作
    public void BillGeneration1() throws Exception {
        List<Qldbzt> qldbzts = billingMapper.selectydztkAll();
        for (Qldbzt qldbzt : qldbzts) {
            /* 江环项目人员先跳过 */
            if (!"江环项目".equals(qldbzt.getZt())) {
                Config config = new Config()
                        // 替换为你的 AccessKey ID
                        .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                        // 替换为你的 AccessKey Secret
                        .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                // 阿里云短信服务的 endpoint
                config.endpoint = "dysmsapi.aliyuncs.com";
                Client client = new Client(config);
                // 构造API请求对象，请替换请求参数值
                SendSmsRequest sendSmsRequest = new SendSmsRequest()
                        .setPhoneNumbers(qldbzt.getSj())
                        .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                        .setTemplateCode("SMS_493285437");  // 模板CODE必须是已审核通过的
                // 获取响应对象
                SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
                // 响应包含服务端响应的 body 和 headers
                System.out.println(com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
            }
        }
        System.out.println("【苏州青澜实业】临近电费出账期，请您登录能源平台进行月度客户数据核查工作，谢谢！");
    }

    /**
     * 转存电表电费和月度载体电费
     * 每月 1 日 1:00:00 执行
     */
    @Scheduled(cron = "0 0 1 1 * ?")
    public void BillGeneration() {
        List<DbdfVO> dbdfVOS = billingMapper.confirmMeterFeeAll();
        for (DbdfVO dbdfVO : dbdfVOS) {
            QldbydbmxVO record = new QldbydbmxVO();
            record.setDbbh(dbdfVO.getDbbh());
            record.setZt(dbdfVO.getZt());
            record.setFjh(dbdfVO.getFjh());
            record.setNf(dbdfVO.getNf());
            record.setYf(dbdfVO.getYf());
            record.setDbyt(dbdfVO.getDbyt());
            record.setQymc(dbdfVO.getQymc());
            record.setKhbh(dbdfVO.getKhbh());
            record.setJfsj(dbdfVO.getJfsj());
            record.setYxa(dbdfVO.getYxa());
            record.setDba(dbdfVO.getDba());
            record.setDbb(dbdfVO.getDbb());
            record.setDbs(dbdfVO.getDbs());
            record.setDbbl(dbdfVO.getDbbl());
            record.setDbjs(dbdfVO.getDbjs());
            record.setDfdj(dbdfVO.getDfdj());
            record.setDbdf(dbdfVO.getDbdf());

            record.setRatio(BigDecimal.ZERO);
            record.setCheckdf(BigDecimal.ZERO);
            record.setTimestamp(new Date());
            record.setTname("Machine");
            List<QldbydbmxVO> existingRecord = billingMapper.selectQldbydbmx(record.getZt(), record.getDbbh(), record.getYf(), record.getNf(), record.getYxa());
            if ((existingRecord != null && !existingRecord.isEmpty())) {
                log.debug("电表月度电费 --> 该月记录已存在, 跳过插入：载体名称: {}, 电表编号: {}, yf: {}, nf: {}", record.getZt(), record.getDbbh(), record.getYf(), record.getNf());
                continue;
            }
            Boolean a = billingMapper.insert(record); // 插入记录
            if (!Boolean.TRUE.equals(a)) {

                throw new RuntimeException("电表月度电费 --> 插入失败：电表编号: " + record.getDbbh() + "，载体名称: " + record.getZt());
            } else {
                log.debug("电表月度电费 --> 插入成功：电表编号: {}, 载体名称: {}, record: {}", record.getDbbh(), record.getZt(), record);
            }
        }
        //查询项目，插入项目月度表
        List<Dbydzt> dbydzts = billingMapper.selectydztAll();
        for (Dbydzt dbydzt : dbydzts) {
            QldbydyzPO record = new QldbydyzPO();
            record.setZt(dbydzt.getZt());
            record.setNf(dbydzt.getNf());
            record.setYf(dbydzt.getYf());
            record.setDbjs(dbydzt.getDbjs());
            record.setDbzy(dbydzt.getDbzy());
            record.setDbgs(dbydzt.getDbgs());
            record.setDbjsdf(dbydzt.getDbjsdf());
            record.setZdf(dbydzt.getZdf());
            record.setDbjsdf(dbydzt.getDbjsdf());
            record.setDbzydf(dbydzt.getDbzydf());
            record.setCheckdf(BigDecimal.ZERO);
            record.setTname("Machine");
            record.setTimestamp(new Date());
            record.setDbgsdf(dbydzt.getDbgsdf());

            // 处理跨年月份
            if (dbydzt.getYf() == 12) {
                record.setJfyf(1);             // 月份重置为1（次年1月）
                record.setJfnf(dbydzt.getNf() + 1); // 年份+1
            } else {
                record.setJfyf(dbydzt.getYf() + 1);
                record.setJfnf(dbydzt.getNf());
            }

            List<QldbydyzPO> existingRecord = billingMapper.selectQldbydbzt(record.getZt(), record.getYf(), record.getNf());
            if ((existingRecord != null && !existingRecord.isEmpty())) {
                log.debug("项目月度账单 --> 该月记录已存在, 跳过插入：zt: {}, yf: {}, nf: {}", record.getZt(), record.getYf(), record.getNf());
                continue;
            }
            Boolean b = billingMapper.insertydzt(record);
            if (!Boolean.TRUE.equals(b)) {
                throw new RuntimeException("项目月度账单 --> 插入失败：载体名称: {}" + record.getZt());
            } else {
                log.info("项目月度账单 --> 已生成月度电费账单：{}", record);
            }
        }
    }

    /**
     * 系统自动生成应收账单, 转存租户电费
     * 每月 1 日 04:00:00 执行
     */
    @Scheduled(cron = "0 0 4 1 * ?")
    public void BillGeneration2() throws Exception {
        List<Dbydydfvckkh> ydkhs = billingMapper.selectydkhAll();
        for (Dbydydfvckkh ydkh : ydkhs) {
            int nf = ydkh.getNf();
            int yf = ydkh.getYf();
            // 格式化年份和月份为"yyyy-MM"格式
            String dateStr = String.format("%d-%02d", nf, yf);
            Date date = DateUtils.getFirstDayOfMonth(dateStr);
            Date lastDate = DateUtils.getLastDayOfMonth(dateStr);
            Date Month15Day = DateUtils.getDay15OfNextMonth(dateStr);
            Qldbykhmx record = new Qldbykhmx();
            record.setZt(ydkh.getZt());
            record.setQymc(ydkh.getQymc());
            record.setKhbh(ydkh.getKhbh());
            record.setKhbha(ydkh.getKhbh());
            record.setHblx(1);
            record.setHklx(ydkh.getHklx());
            record.setDbyt(ydkh.getDbyt());
            record.setNf(nf);
            record.setYf(yf);
            record.setHkje(ydkh.getZdf());
            record.setYsje(BigDecimal.ZERO);
            record.setWsje(ydkh.getZdf());
            record.setHkzt("未收款");
            record.setHkrq(Month15Day);
            record.setHkks(date);
            record.setHkjs(lastDate);
            record.setYx(1);
            record.setTname("Machine");
            record.setTimestamp(new Date());
            record.setHkbz("");
            record.setDbjs(ydkh.getDbjs());
            List<Qldbykhmx> existingRecord = billingMapper.selectExistingRecord(record.getZt(), record.getKhbh(), record.getYf(), record.getNf(), record.getHklx());
            if ((existingRecord != null && !existingRecord.isEmpty())) {
                log.debug("生成账单 --> 该月记录已存在，跳过插入：载体: {}, 客户编号: {}, 月份: {}, 年份: {}", record.getZt(), record.getKhbh(), record.getYf(), record.getNf());
                continue;
            }
            // 插入
            Boolean a = billingMapper.insertkh(record);
            if (!Boolean.TRUE.equals(a)) {
                throw new RuntimeException("生成账单 --> 插入失败：客户编号: " + record.getKhbh() + "，客户名称: " + record.getQymc());
            } else {
                log.debug("生成账单 --> 插入成功：客户编号: {}, 客户名称: {}, record: {}", record.getKhbh(), record.getQymc(), record);
            }
        }
    }


    /**
     * 推送账单生成提醒
     * 每月 1 日 14:00:00 执行
     */
    @Scheduled(cron = "0 0 14 1 * ?")
    public void BillGenerationReminder() throws Exception {
        log.info("----- 开始推送账单生成提醒 -----");
        List<Dbydydfvckkh> ydkhs = billingMapper.selectydkhAll();
        for (Dbydydfvckkh ydkh : ydkhs) {
            int nf = ydkh.getNf();
            int yf = ydkh.getYf();
            // 格式化年份和月份为"yyyy-MM"格式
            String dateStr = String.format("%d-%02d", nf, yf);
            Date date = DateUtils.getFirstDayOfMonth(dateStr);
            Date lastDate = DateUtils.getLastDayOfMonth(dateStr);
            Date Month15Day = DateUtils.getDay15OfNextMonth(dateStr);
            Qldbykhmx record = new Qldbykhmx();
            record.setZt(ydkh.getZt());
            record.setQymc(ydkh.getQymc());
            record.setKhbh(ydkh.getKhbh());
            record.setKhbha(ydkh.getKhbh());
            record.setHblx(1);
            record.setHklx(ydkh.getHklx());
            record.setDbyt(ydkh.getDbyt());
            record.setNf(nf);
            record.setYf(yf);
            record.setHkje(ydkh.getZdf());
            record.setYsje(BigDecimal.ZERO);
            record.setWsje(ydkh.getZdf());
            record.setHkzt("未收款");
            record.setHkrq(Month15Day);
            record.setHkks(date);
            record.setHkjs(lastDate);
            record.setYx(1);
            record.setTname("Machine");
            record.setTimestamp(new Date());
            record.setHkbz("");
            record.setDbjs(ydkh.getDbjs());

            List<String> phoneList = billingMapper.selectSj(ydkh.getKhbh(), ydkh.getZt());
            /* 江环项目人员先跳过 */
            if (!"江环项目".equals(ydkh.getZt())) {
                if (CollectionUtils.isNotEmpty(phoneList)) {
                    // 动态生成模板参数JSON字符串
                    String templateParam = String.format(
                            "{\"nf\":\"%s\",\"yf\":\"%s\",\"dbs\":\"%s\",\"hklx\":\"%s\",\"zdf\":\"%s\"}",
                            nf, yf, ydkh.getDbs(), ydkh.getHklx(), ydkh.getZdf()
                    );

                    Config config = new Config()
                            // 替换为你的 AccessKey ID
                            .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                            // 替换为你的 AccessKey Secret
                            .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                    // 阿里云短信服务的 endpoint
                    config.endpoint = "dysmsapi.aliyuncs.com";
                    Client client = new Client(config);

                    phoneList.forEach(sj -> {
                        if (StringUtils.isBlank(sj) || "15301547036".equals(sj)) {
                            return;
                        }
                        // 构造API请求对象，请替换请求参数值
                        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                                .setPhoneNumbers(sj)
                                .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                                .setTemplateCode("SMS_493730113")  // 模板CODE必须是已审核通过的
                                .setTemplateParam(templateParam);

                        // 获取响应对象
                        SendSmsResponse sendSmsResponse = null;
                        try {
                            sendSmsResponse = client.sendSms(sendSmsRequest);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }

                        // 响应包含服务端响应的 body 和 headers
                        log.info("手机号: {}, 发送结果: {}", sj, com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
                    });

                }
                log.info("【苏州青澜实业】尊敬的客户：" + nf + "年" + yf + "月 使用电量" + ydkh.getDbs() + "度，" + ydkh.getHklx() + ydkh.getZdf() + "元。请您于15日内完成电费缴纳。");
//            微信电费缴纳提醒
//            电费账期：2025-7
//            本期用量：552度
//            应缴电费：750元
//            请您于15日内完成电费缴纳。
                //匹配跟新公众号openid为一方法
                String toUserOpenId = billingMapper.selectOpenid(ydkh.getKhbh(), ydkh.getZt());
                if (StringUtils.isNotBlank(toUserOpenId)) {
                    String accessToken = templateController.getWxTemplate();
                    String templateId = "2QuPUhAhRJs2sqY0PO2DhLaSfw4bAQsXhbNcfAfwp-0";
                    String month = ydkh.getNf() + "-" + ydkh.getYf();
                    String je = ydkh.getZdf().toString();
                    LocalDate localDate = Month15Day.toInstant()
                            .atZone(ZoneId.systemDefault()) // 推荐显式指定时区，如 ZoneId.of("Asia/Shanghai")
                            .toLocalDate();
                    // 3.2 定义目标格式：yyyy-MM-dd（年-月-日，补零对齐）
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    // 3.3 格式化得到最终字符串（如 "2025-07-15"）
                    String formattedDate = localDate.format(formatter);
                    Map<String, TemplateMessageSender.TemplateData> templateData = prepareTemplateData(ydkh.getKhbh(), ydkh.getHklx(), month, je, formattedDate);
                    templateController.sendWechatTemplateMessage(accessToken, toUserOpenId, templateId, templateData);
                }
            }
        }
    }


    /**
     * 每月提醒客户欠费缴纳
     * 每月 10 日 14:00:00 执行
     */
    @Scheduled(cron = "0 0 14 10 * ?")
    public void monthOneReminder() throws Exception {
        List<Dbysdba1t> dbysdba1ts = billingMapper.selectdba1tAll();
        for (Dbysdba1t t1 : dbysdba1ts) {
            if (t1.getTxlx() == 1) {
                List<String> phoneList = billingMapper.selectSj(t1.getKhbh(), t1.getZt());
                if (CollectionUtils.isNotEmpty(phoneList)) {
                    /* 江环项目人员先跳过 */
                    if (!"江环项目".equals(t1.getZt())) {
                        // 动态生成模板参数JSON字符串
                        String templateParam = String.format(
                                "{\"qfje\":\"%s\"}", t1.getQfje()

                        );

                        Config config = new Config()
                                // 替换为你的 AccessKey ID
                                .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                                // 替换为你的 AccessKey Secret
                                .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                        // 阿里云短信服务的 endpoint
                        config.endpoint = "dysmsapi.aliyuncs.com";
                        Client client = new Client(config);

                        phoneList.forEach(sj -> {
                            // 构造API请求对象，请替换请求参数值
                            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                                    .setPhoneNumbers(sj)
                                    .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                                    .setTemplateCode("SMS_493735125")  // 模板CODE必须是已审核通过的
                                    .setTemplateParam(templateParam);

                            // 获取响应对象
                            SendSmsResponse sendSmsResponse = null;
                            try {
                                sendSmsResponse = client.sendSms(sendSmsRequest);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }

                            String toUserOpenId = billingMapper.selectOpenid(t1.getKhbh(), t1.getZt());
                            if (StringUtils.isNotBlank(toUserOpenId)) {
                                String accessToken = null;
                                try {
                                    accessToken = templateController.getWxTemplate();
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }
                                String templateId = "Oa791CL-2tOyiqrTVfWooRlocXMZpr2N2XUfRKcGZak";
                                Map<String, TemplateMessageSender.TemplateData> templateData = prepareTemplateDataQF(t1.getQymc(), t1.getQfje());
                                templateController.sendWechatTemplateMessage(accessToken, toUserOpenId, templateId, templateData);
                            }

                            // 响应包含服务端响应的 body 和 headers
                            log.info("OpenId: {}, 发送结果：{}", toUserOpenId, com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
                        });


                    }
                }
                log.info("【苏州青澜实业】尊敬的客户：您的当前电费总额 " + t1.getQfje() + "元，您已欠费，请尽快缴纳，以免因欠费影响您的正常用电权益");
                QldbqyinfoPO qldbqyinfoPO = new QldbqyinfoPO();
                qldbqyinfoPO.setKhbh(t1.getKhbh());
                qldbqyinfoPO.setQftx(0);
                qldbqyinfoPO.setQftxrq(null);
                Boolean b = wxMapper.updateQldbqyinfo(qldbqyinfoPO);
                if (!b) {
                    throw new RuntimeException("更新失败：客户编号: {}" + t1.getKhbh());
                }
            }
        }
    }


    /**
     * 每日提醒客户欠费缴纳
     * 每日 14:00:00 执行
     */
    /*@Scheduled(cron = "0 0 14 * * ?")
    public void DayOneReminder() throws Exception {
        List<Dbysdba1t> dbysdba1ts = billingMapper.selectdba1tAll();
        for (Dbysdba1t t1 : dbysdba1ts) {
            if (t1.getTxlx() == 2) {
                String sj=billingMapper.selectSj(t1.getKhbh(),t1.getZt());
                *//* 江环项目人员先跳过 *//*
                if (!"江环项目".equals(t1.getZt())) {
                    if (StringUtils.isNotEmpty(sj)) {
                        // 动态生成模板参数JSON字符串
                        String templateParam = String.format(
                                "{\"qfje\":\"%s\"}", t1.getQfje()
                        );
                        Config config = new Config()
                                // 替换为你的 AccessKey ID
                                .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                                // 替换为你的 AccessKey Secret
                                .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                        // 阿里云短信服务的 endpoint
                        config.endpoint = "dysmsapi.aliyuncs.com";
                        Client client = new Client(config);
                        // 构造API请求对象，请替换请求参数值
                        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                                .setPhoneNumbers(sj)
                                .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                                .setTemplateCode("SMS_493735125")  // 模板CODE必须是已审核通过的
                                .setTemplateParam(templateParam);

                        // 获取响应对象
                        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

                        // 响应包含服务端响应的 body 和 headers
                        System.out.println(com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
                    }
                    System.out.println("【苏州青澜实业】尊敬的客户：您的当前电费总额 " + t1.getQfje() + "元，您已欠费，请尽快缴纳，以免因欠费影响您的正常用电权益");
                }
            }
        }
    }*/

    /**
     * 每日提醒客户欠费缴纳
     * 每天 14:00:00 执行
     */
    /*@Scheduled(cron = "0 0 14 * * ?")
    public void DayOneReminder1() throws Exception {
        List<Dbysdba1t> dbysdba1ts = billingMapper.selectdba1tRAll();
        for (Dbysdba1t t1 : dbysdba1ts) {
            *//* 江环项目人员先跳过 *//*
            if (!"江环项目".equals(t1.getZt())) {
                if (t1.getTxlx() == 1) {
                    System.out.println("【苏州青澜实业】客户" + t1.getQymc() + "当前电费欠费值为：" + t1.getQfje() + "元，请及时与其沟通进行充值缴费，谢谢！");
                    Integer lb = 3;
                    List<Qldbzt> qldbzts = billingMapper.selectQldbzt(t1.getZt(), lb);
                    if (qldbzts != null || qldbzts.isEmpty()) {
                        for (Qldbzt qldbzt : qldbzts) {
                            // 动态生成模板参数JSON字符串
                            String templateParam = String.format(
                                    "{\"qymc\":\"%s\",\"qfje\":\"%s\"}", t1.getQymc(), t1.getQfje()
                            );
                            Config config = new Config()
                                    // 替换为你的 AccessKey ID
                                    .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                                    // 替换为你的 AccessKey Secret
                                    .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                            // 阿里云短信服务的 endpoint
                            config.endpoint = "dysmsapi.aliyuncs.com";
                            Client client = new Client(config);
                            // 构造API请求对象，请替换请求参数值
                            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                                    .setPhoneNumbers(qldbzt.getSj())
                                    .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                                    .setTemplateCode("SMS_493720137")  // 模板CODE必须是已审核通过的
                                    .setTemplateParam(templateParam);

                            // 获取响应对象
                            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

                            // 响应包含服务端响应的 body 和 headers
                            System.out.println(com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
                        }
                    }
                }
                if (t1.getTxlx() == 2) {
                    System.out.println("【苏州青澜实业】客户" + t1.getQymc() + "当前电费欠费值为：" + t1.getQfje() + "元，请及时与其沟通进行充值缴费，谢谢！");
                    Integer lb = 6;
                    List<Qldbzt> qldbzts = billingMapper.selectQldbzt(t1.getZt(), lb);
                    if (qldbzts != null || qldbzts.isEmpty()) {
                        for (Qldbzt qldbzt : qldbzts) {
                            // 动态生成模板参数JSON字符串
                            String templateParam = String.format(
                                    "{\"qymc\":\"%s\",\"qfje\":\"%s\"}", t1.getQymc(), t1.getQfje()
                            );
                            Config config = new Config()
                                    // 替换为你的 AccessKey ID
                                    .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                                    // 替换为你的 AccessKey Secret
                                    .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                            // 阿里云短信服务的 endpoint
                            config.endpoint = "dysmsapi.aliyuncs.com";
                            Client client = new Client(config);
                            // 构造API请求对象，请替换请求参数值
                            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                                    .setPhoneNumbers(qldbzt.getSj())
                                    .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                                    .setTemplateCode("SMS_493720137")  // 模板CODE必须是已审核通过的
                                    .setTemplateParam(templateParam);

                            // 获取响应对象
                            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

                            // 响应包含服务端响应的 body 和 headers
                            System.out.println(com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
                        }
                    }
                }
                if (t1.getTxlx() == 3) {
                    Integer lb = 8;
                    List<Qldbzt> qldbzts = billingMapper.selectQldbzt(t1.getZt(), lb);
                    if (qldbzts != null || qldbzts.isEmpty()) {
                        for (Qldbzt qldbzt : qldbzts) {
                            // 动态生成模板参数JSON字符串
                            String templateParam = String.format(
                                    "{\"qymc\":\"%s\",\"qfje\":\"%s\"}", t1.getQymc(), t1.getQfje()
                            );
                            Config config = new Config()
                                    // 替换为你的 AccessKey ID
                                    .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                                    // 替换为你的 AccessKey Secret
                                    .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                            // 阿里云短信服务的 endpoint
                            config.endpoint = "dysmsapi.aliyuncs.com";
                            Client client = new Client(config);
                            // 构造API请求对象，请替换请求参数值
                            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                                    .setPhoneNumbers(qldbzt.getSj())
                                    .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                                    .setTemplateCode("SMS_493870128")  // 模板CODE必须是已审核通过的
                                    .setTemplateParam(templateParam);
                            // 获取响应对象
                            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
                            // 响应包含服务端响应的 body 和 headers
                            System.out.println(com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
                        }
                    }
                }
            }
        }
    }*/

    /**
     * 准备模板消息数据
     */
    public Map<String, TemplateMessageSender.TemplateData>
    prepareTemplateData(String qymc, String hklx, String month, String je, String hkrq) {
        Map<String, TemplateMessageSender.TemplateData> data = new HashMap<>();

        // 企业名称
        TemplateMessageSender.TemplateData billType = new TemplateMessageSender.TemplateData();
        billType.setValue(qymc);
        billType.setColor("#173177");
        data.put("thing15", billType);

        // 账单名称
        TemplateMessageSender.TemplateData totalAmount = new TemplateMessageSender.TemplateData();
        totalAmount.setValue(hklx);
        totalAmount.setColor("#173177");
        data.put("thing10", totalAmount);


        // 账单日期
        TemplateMessageSender.TemplateData roomNo = new TemplateMessageSender.TemplateData();
        roomNo.setValue(month);
        roomNo.setColor("#173177");
        data.put("time32", roomNo);

        // 账单金额
        TemplateMessageSender.TemplateData chargeMonth = new TemplateMessageSender.TemplateData();
        chargeMonth.setValue(je);
        chargeMonth.setColor("#173177");
        data.put("amount4", chargeMonth);

        // 应缴日期
        TemplateMessageSender.TemplateData currentReading = new TemplateMessageSender.TemplateData();
        currentReading.setValue("请您于" + hkrq + "日内完成电费缴纳");
        currentReading.setColor("#173177");
        data.put("time22", currentReading);
        return data;
    }

    //欠费通知
    public Map<String, TemplateMessageSender.TemplateData>
    prepareTemplateDataQF(String qymc, BigDecimal qfje) {
        Map<String, TemplateMessageSender.TemplateData> data = new HashMap<>();

        // 姓名
        TemplateMessageSender.TemplateData billType = new TemplateMessageSender.TemplateData();
        billType.setValue(qymc);
        billType.setColor("#173177");
        data.put("thing1", billType);

        // 欠费金额
        TemplateMessageSender.TemplateData totalAmount = new TemplateMessageSender.TemplateData();
        totalAmount.setValue(qfje.toString());
        totalAmount.setColor("#173177");
        data.put("amount3", totalAmount);
        return data;

    }
}
